package edu.washington.ling.syntric.io;

import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;

import edu.washington.ling.syntric.struct.tree.Token;
import edu.washington.ling.syntric.struct.tree.Tree;


public class TreeWriterCoNLL extends TreeWriter {

	public String getFeatsForToken(Token t) {
		ArrayList<String> elems = new ArrayList<String>();
		for (String feat: t.getFeatures()) {
			if (!t.isDerrived(feat)) {
				elems.add(String.format("%s:%s", feat, t.getValue(feat)));
			}
		}
		return StringUtils.join(elems, "|");
	}
	public String getHeadForToken(Token t, Tree tree) {
		String head = "0";
		if (t.hasDSHead()) {
			Token parent = t.getDSHead();
			int headIdx = tree.getTokenPosition(parent);
			head = Integer.toString(headIdx + 1);
		}
		return head;
	}
	public String getLineForToken(Token t, Tree tree) {
		String id = Integer.toString(tree.getTokenPosition(t) + 1);
		String form = t.getWord();
		String lemma = "-";
		String cpostag = t.getTag();
		String postag = t.getTag();
		String feats = getFeatsForToken(t);
		String head = getHeadForToken(t, tree);
		String deprel = t.getDSRelation();
		String phead = "-";
		String pdeprel = "-";
		String[] elems = {id, form, lemma, cpostag, postag, 
							  feats, head, deprel, phead, pdeprel};
		return StringUtils.join(elems, "\t");
	}
	@Override
	public TreeRepresentation writeTree(Tree tree) {
		ArrayList<String> lines = new ArrayList<String>();
		for (Token t: tree.getTokenList()) {
			lines.add(getLineForToken(t, tree));
		}
		return new TreeRepresentation(lines, tree.getLayer(), "conll");
	}

}
